package com.egg.demo.controller.web;


import cn.hutool.core.date.DateUtil;
import com.egg.common.core.model.controller.WebController;
import com.egg.common.core.model.response.ResponseData;
import com.egg.common.util.IdGenUtil;
import com.egg.common.util.OptionalUtil;
import com.egg.common.util.SmallExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Api(tags = WebController.API_PREFIX + "EXCEL")
@RestController
@RequestMapping("/excel")
public class WebExcelController extends WebController {


    @Data
    public static class ExcelTest {


        @ApiModelProperty(value = "时间")
        private Date date;

        @ApiModelProperty(value = "字符串")
        private String str;

        @ApiModelProperty(value = "字符串数字")
        private String strL;

        @ApiModelProperty(value = "字符串时间")
        private String strDate;

        /**
         * 会导致精度丢失
         */
        @ApiModelProperty(value = "长数字")
        private Long l;

        @ApiModelProperty(value = "数字")
        private Integer i;


    }


    @ApiOperation(value = "导出")
    @GetMapping(produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void get(
            @ApiParam(value = "文件名") @RequestParam(value = "filename", required = false) String filename
    ) {
        List<ExcelTest> erList = new ArrayList<>();
        for (int i = 0; i <= 50; i++) {
            ExcelTest er = new ExcelTest();
            erList.add(er);
            er.setDate(new Date());
            er.setI(i);
            er.setL(IdGenUtil.longId());
            er.setStr(IdGenUtil.strId());
            er.setStrL(IdGenUtil.longId().toString());
            er.setStrDate(DateUtil.now());
        }
        SmallExcelUtil.writerOnApiModelProperty(ExcelTest.class, erList, OptionalUtil.build(filename));
    }

    @ApiOperation(value = "导入")
    @PostMapping
    public ResponseData<List<ExcelTest>> post(
            @ApiParam(value = "导入文件") @RequestParam(value = "file") MultipartFile file
    ) throws IOException {
        List<ExcelTest> erList = SmallExcelUtil.readOnApiModelProperty(ExcelTest.class, file.getInputStream());
        return ResponseData.success(erList);
    }


}

